package Servlet;

import BaseQuery.BaseQuery;
import Bean.Employee;
import Bean.PageBean;
import Utils.IOUtils;
import Utils.JsonToObjUtils;
import com.alibaba.fastjson.JSONObject;
import dao.EmployeeDao;
import serve.EmployeeServe;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/emp2")
public class ServerletEmployee2 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json;charset=UTF-8");
		String what= req.getParameter("what");
		System.out.println(what);

		EmployeeServe employeeServe=new EmployeeServe();
		String respStr=null;

		try {
			if("add".equals(what)) {
				String jsonStr= IOUtils.readStr(req.getInputStream());
				Employee employee= JsonToObjUtils.jsonStrToObj(jsonStr, Employee.class);
				boolean add=employeeServe.add(employee);
				respStr=add?"success":"failed";
			} else if("update".equals(what)) {
				String jsonStr= IOUtils.readStr(req.getInputStream());
				Employee employee= JsonToObjUtils.jsonStrToObj(jsonStr, Employee.class);
				boolean update=employeeServe.update(employee);
				respStr=update?"success":"failed";

			} else if("del".equals(what)) {
				String empno=req.getParameter("empno");
				boolean del=employeeServe.delete(Integer.parseInt(empno));
				respStr=del?"success":"failed";
			} else if("getById".equals(what)) {
				String empno=req.getParameter("empno");
				Employee employee=employeeServe.getById(Integer.parseInt(empno));
				respStr= JSONObject.toJSONString(employee);

			} else if("page".equals(what)) {
				String jsonStr=IOUtils.readStr(req.getInputStream());
				 BaseQuery baseQuery = JsonToObjUtils.jsonStrToObj(jsonStr, BaseQuery.class);
				PageBean<Employee> pageBean=employeeServe.getByPage(baseQuery);
				respStr=JSONObject.toJSONString(pageBean);

			} else {
				respStr=" no service";
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		resp.getWriter().write(respStr);
	}
}
